import { resourceEntApi } from '@/api';
import { EnCourseWareGroup, EnResourceNameGroup, pageOpeTypeEnum, WordEnum } from '@/common';
import { useAppSelector } from '@/redux/store';
// import ExaminationBatchUpload from '@/components/resourceLibraryComp/ExaminationAddOrEditComp/ExaminationBatchUpload';
import ExaminationItem from '@/components/resourceLibraryComp/ExaminationAddOrEditComp/ExaminationItem';
import { Button, Form, message } from 'antd';
import { useEffect, useMemo, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { YmAddPageLayout, type YmAddPageLayoutProps } from 'ym-design';

const formItemLayout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 18 },
};

const { PaneItem } = YmAddPageLayout;

const plantType = process.env.processEnvDetail.REACT_APP_PLATFORM;
function AddSChoiceQue() {
  const [searchParam] = useSearchParams();
  const navigator = useNavigate();
  const type = searchParam.get('type');
  const parentId = searchParam.get('parentId');
  const { entId } = useAppSelector((state) => state.loginEnt);
  const examinationId = searchParam.get('resourceId');
  const [collPanesActiveKeys, setCollPanesActiveKeys] = useState([0, -1]); // 打开的题目的keys
  const [answerMap, setAnswerMap] = useState<Map<number, string[]>>(new Map([[0, ['A', 'B', 'C', 'D']]])); // 考题 答案 options
  const [form] = Form.useForm();
  const [loadingDetail, setLoadingDetail] = useState({
    subBtnDis: false,
    viewLoading: false,
  });

  const goBackToList = () => {
    const x = plantType === 'boss' ? '/resourceLibrary/' : '/cusResLib/';
    navigator(x + 'examination', { state: { activeTab: 'sChoiceQue' } });
  };

  //添加、删除选项时，设置 答案 options
  const handleAnswerMapSet = (
    currExaIndex: number,
    prevSelectItemListLength: number,
    type?: string,
    newMap?: Map<number, string[]>,
  ) => {
    let currSelectItemListLength;
    switch (type) {
      case 'add':
        currSelectItemListLength = prevSelectItemListLength + 1;
        break;
      case 'remove':
        currSelectItemListLength = prevSelectItemListLength - 1;
        break;
      default:
        currSelectItemListLength = prevSelectItemListLength;
        break;
    }

    const finalMap = newMap ? newMap : answerMap;

    const answerOptions = [];
    for (let i = 0; i < currSelectItemListLength; i++) {
      answerOptions.push(WordEnum[i]);
    }
    finalMap.set(currExaIndex, answerOptions);
    return finalMap;
  };

  // 删除题目
  const handleRemoveExamination = (exaIndex: number) => {
    const { examinationList } = form.getFieldsValue();
    examinationList.splice(exaIndex, 1);
    form.setFieldsValue({
      examinationList: [...examinationList],
    });
    const tempAnswerMap = new Map(); //
    examinationList.forEach((listItem: any, index: number) => {
      const selectItemListLength = listItem.selectItemList.length;
      handleAnswerMapSet(index, selectItemListLength, undefined, tempAnswerMap);
    });
    // console.log('--删除--handleRemoveExamination--tempAnswerMap--：', tempAnswerMap);
    setAnswerMap(tempAnswerMap);
  };

  // 添加题目
  const addQuestion = () => {
    const { examinationList } = form.getFieldsValue();
    const currActiveExaFieldIndex = examinationList.length;
    form.setFieldsValue({
      examinationList: [
        ...examinationList,
        { content: undefined, selectItemList: [undefined, undefined, undefined, undefined] },
      ],
    });
    answerMap.set(currActiveExaFieldIndex, ['A', 'B', 'C', 'D']);
    setAnswerMap(answerMap);
    collPanesActiveKeys.push(currActiveExaFieldIndex);
    const newArr = Array.from(new Set<number>([...collPanesActiveKeys]));
    setCollPanesActiveKeys(newArr);
  };

  /**
   *  批量上传题目
   * @param newExaminationList
   * @param type  1:覆盖，2：追加
   */
  const handleSetFormValues = (newExaminationList: any[], type: number) => {
    const currExaminationList = form.getFieldValue('examinationList');
    const tempExaminationList = type === 1 ? newExaminationList : [...currExaminationList, ...newExaminationList];
    form.setFieldValue('examinationList', tempExaminationList);
    const tempAnswerMap = new Map(); //
    const tempCollPanesActiveKeys: number[] = [];
    tempExaminationList.forEach((listItem: any, index: number) => {
      tempCollPanesActiveKeys.push(index);
      const selectItemListLength = listItem.selectItemList.length;
      handleAnswerMapSet(index, selectItemListLength, undefined, tempAnswerMap);
    });
    setAnswerMap(tempAnswerMap);
    setCollPanesActiveKeys([...tempCollPanesActiveKeys, -1]);
  };

  // 当前题目不在 collPanesActiveKeys中时，有error，就要打开
  function _openErrorExaminationPane(err: any) {
    const { errorFields } = err;
    const errorStr: string = errorFields[0].errors[0];
    const kuo1 = errorStr.indexOf('【');
    const kuo2 = errorStr.indexOf('】');
    const currNumber = Number(errorStr.substring(kuo1 + 1, kuo2));
    const errorIndex = collPanesActiveKeys.findIndex((val) => val === currNumber);
    if (errorIndex > -1) return;
    collPanesActiveKeys.push(currNumber);
    const newArr = Array.from(new Set<number>([...collPanesActiveKeys]));
    setCollPanesActiveKeys(newArr);
  }

  // 提交
  const formSub = () => {
    setLoadingDetail({ subBtnDis: true, viewLoading: true });
    form
      .validateFields()
      .then((values) => {
        // console.log('--AddSChoice--values--:', values);
        const { examinationList } = values;
        const quesArrs = examinationList.map((listItem: any) => {
          const newSelectItemList = listItem.selectItemList.map((answerItem: any, answerIndex: number) => ({
            itemValue: answerItem.itemValue,
            itemCode: WordEnum[answerIndex],
          }));
          const newAnwserItemList = [listItem.anwserItemList];
          return {
            ...listItem,
            // anwserItemList: newAnwserItemList,
            selectItemList: newSelectItemList,
            answerItemList: newAnwserItemList,
            questionType: '100',
            sourceType: '100',
            entId,
            parentId,
            // type: '100',
          };
        });
        const subData = {
          crateQuestionDtoList: [],
        };
        subData.crateQuestionDtoList = quesArrs;
        console.log('--AddSChoice--subData--:', subData);
        let requestApi;
        if (type === pageOpeTypeEnum['add']) {
          requestApi = resourceEntApi.createExamination(subData);
        } else if (type === pageOpeTypeEnum['edit']) {
          const editSubData = subData.crateQuestionDtoList[0];
          editSubData.questionId = examinationId;
          requestApi =
            plantType === 'boss'
              ? resourceEntApi.updateExamination(editSubData)
              : resourceEntApi.createExamination(subData);
        } else {
          return message.error('type 未定义');
        }
        requestApi
          .then((res: any) => {
            const { code, msg } = res;
            if (code === '200') {
              message.success(msg || `${type === pageOpeTypeEnum['add'] ? '添加' : '编辑'}成功`);
              //保存
              goBackToList();
            } else {
              message.error(msg);
            }
          })
          .catch((err: any) => {
            console.log('--AddSChoice--_formSub--err--:', err);
          })
          .finally(() => {
            setLoadingDetail({ subBtnDis: false, viewLoading: false });
          });
      })
      .catch((err) => {
        console.log('--AddSChoice--form--err--:', err);
        setLoadingDetail({ subBtnDis: false, viewLoading: false });
        _openErrorExaminationPane(err);
      });
  };

  const operationFooter = useMemo(() => {
    const operationBtn = [
      <Button key="subOnce" type="primary" size="small" disabled={loadingDetail.subBtnDis} onClick={formSub}>
        保存
      </Button>,
    ];
    if (type === pageOpeTypeEnum['add']) {
      operationBtn.unshift(
        <Button key="addExa" type="primary" size="small" disabled={loadingDetail.subBtnDis} onClick={addQuestion}>
          添加考题
        </Button>,
      );
    }
    return operationBtn;
  }, [type, loadingDetail, collPanesActiveKeys, answerMap]);

  useEffect(() => {
    if (type === pageOpeTypeEnum['add']) {
      form.setFieldsValue({
        examinationList: [{ content: undefined, selectItemList: [undefined, undefined, undefined, undefined] }],
      });
    } else {
      resourceEntApi.getExaminationById({ questionId: examinationId }).then((res: any) => {
        // console.log('--Examination--res--:', res);
        const {
          data: { content, answerList, selectItemDtoList },
        } = res;
        let selectItemList: any[] = [];
        let anwserItemStr = undefined;
        try {
          selectItemList = selectItemDtoList.map((listItem: any) => ({ itemValue: listItem.itemValue }));
          anwserItemStr = answerList[0];
        } catch (err) {
          console.log('---Examination--jsonParse--err--:', err);
        }
        const tempAnswerMap = new Map();
        handleAnswerMapSet(0, selectItemList.length, undefined, tempAnswerMap);
        setAnswerMap(tempAnswerMap);

        const tempExaminationList = [{ content, selectItemList, anwserItemList: anwserItemStr }];
        form.setFieldValue('examinationList', tempExaminationList);
      });
    }
  }, []);

  const layoutParams: YmAddPageLayoutProps = useMemo(
    () => ({
      leftOperation: {
        onBack: () => {
          goBackToList();
        },
      },
      rightOperationDom: operationFooter,
      destroyInactiveTabPane: false,
    }),
    [operationFooter],
  );

  //2023-06-10 最终判断 Form.List 和 拖拽 一起用就是有bug
  // 放弃，放弃
  return (
    <YmAddPageLayout {...layoutParams}>
      <PaneItem
        tabKey="tab1"
        label={
          (type === pageOpeTypeEnum['add'] ? '添加' : '编辑') +
          '考题（' +
          EnResourceNameGroup[Number(EnCourseWareGroup['sChoiceQue'])] +
          '）'
        }
        className="pane_tab1"
      >
        <div className="ym_detail_grid">
          <Form layout="horizontal" labelAlign="right" size="large" form={form} {...formItemLayout}>
            <Form.List name="examinationList">
              {(exaFields, { add: exaAdd, remove: exaRemove, move: exaMove }, { errors }) =>
                exaFields.map((exaField, exaIndex) => (
                  <ExaminationItem
                    exaFields={exaFields}
                    examinationType="sChoiceQue"
                    title={`题目${exaIndex + 1}`}
                    key={exaField.key}
                    exaField={exaField}
                    exaIndex={exaIndex}
                    answerMap={answerMap}
                    onAnswerMapSet={(currExaIndex, prevSelectItemListLength, type) => {
                      const newAnswerMap = handleAnswerMapSet(currExaIndex, prevSelectItemListLength, type);
                      setAnswerMap(newAnswerMap);
                    }}
                    collPanesActiveKeys={collPanesActiveKeys}
                    onSetCollPanesActiveKeys={setCollPanesActiveKeys}
                    onRemoveExamination={handleRemoveExamination}
                  />
                ))
              }
            </Form.List>
          </Form>
        </div>
      </PaneItem>
    </YmAddPageLayout>
  );
}

export default AddSChoiceQue;
